import React, { Component } from 'react';
import {
  Row,
  Col,
  Card,
  Button,
  Form,
  Input,
  DatePicker,
}
  from 'antd';
import { connect } from 'dva';
import Cookies from "js-cookie";
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardAsyncTable from 'scd/lib/StandardAsyncTable';
import Ellipsis from '@/components/Ellipsis'
import { AsyncSelect } from 'scd';
import moment from 'moment';
import { formatParams, formatDate, openWindow } from '@/utils'
import styles from './index.less'

const { RangePicker } = DatePicker;

const SockJS = window.SockJS;
const Stomp = window.Stomp;
let sock, client;

const tabList=(count) => [
  {
    key: 'todolist',
    tab: (
      <span>
        待办事项 { count > 0 &&  <span style={{ fontSize: 14 }}>({count})</span> }
      </span>
    ),

  },
  {
    key: 'havedolist',
    tab: (
      <span>
        已办事项
      </span>
    ),
  },
];

const columns=(context) => [
  {
    key: 'content',
    title: '待办事项',
    //width:'20%',
    render: (text, record) => (
      <Ellipsis lines={1}>
        <a
          //href={record.seeUrl || '###'}
          onClick={() => context.handleTodoDetail(record)}
        >
          {
            record.content
          }
          {/* {
            record.content.length > 30 ? record.content.substring(0, 30) + '...' : record.content
          } */}
        </a>
      </Ellipsis>
    )
  },
  {
    key: 'type',
    title: '待办类型',
    width: '200px',
    render: (text, record) =>{
      return <span style={{ color: '#999' }}>{record.name}</span>
    }
  },
  {
    key: 'companyName',
    title: '公司',
    width: '300px',
    render: (text, record) => (
      <span style={{ color: '#999' }}>{record.companyName}</span>
    )
  },
  {
    key: 'serviceName',
    title: '产品线',
    width: '300px',
    render: (text, record) => (
      <span style={{ color: '#999' }}>{record.serviceName}</span>
    )
  },
  {
    key: 'createTime',
    title: '日期',
    width: '150px',
    render: (text, record) => (
      <span style={{ color: '#999' }}>{record.createTime && formatDate(record.createTime)}</span>
    )
  },
]

let websocket = null;

@Form.create()
@connect(({ home, global }) => ({
  home,
  information: global.information,
}))
class Dashboard extends Component {

  state={
    activeKey: 'todolist',
    updateKey: Date.now(),
    formValues: {},
  };

  handleTodoDetail=(record) =>{
    // [
    //   {"name":"用户加入组织","code":"BL001"},
    //   {"name":"邀请公司加入组织","code":"BL002"},
    //   {"name":"公司创建审核","code":"BL003"},
    //   {"name":"公司变更审核","code":"BL004"},
    //   {"name":"实名认证","code":"BL005"},
    //   {"name":"邀请公司加入组织","code":"BL006"},
    //   {"name":"公司申请加入组织","code":"BL007"}
    // ]
    // if (record.companyCode ==='BL001'){
    //     dispatch({
    //         type: 'todo/todoInfo',
    //         payload:{
    //           list: [record.id]
    //         },
    //     })
    //     .then(msg => {
    //         message.success(msg);
    //     })
    //     .catch(errMsg => {
    //         message.error(errMsg);
    //     });
    // }
    //history.push(`/todoList/detail?id=${record.id}`)
    //window.location.href=record.seeUrl;

    //this.props.history.push(`/dashboard/todoDetail?companyId=${record.companyCode}&status=${record.status}`)
    openWindow(`/dashboard/todoDetail?companyId=${record.companyCode}&serialNo=${record.serialNo}&code=${record.type}&status=${record.status}&applicant=${record.name}&createTime=${record.createTime}&createUser=${record.createUser}`)

  }

  getKeyShowTemplate=() => {
    const { dispatch }=this.props
    dispatch({
      type: 'home/fetchCount',
      payload: {
        status: 0
      }
    });
  }

  onTabChange=(key, type) => {
    this.setState({
      [type]: key,
    }, () => {
      this.getKeyShowTemplate()
    });
  };

  handleSubmit=(e) => {
    e && e.preventDefault && e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        for(let key in values){

          if(Array.isArray( values[key] ) && values[key].length ===2 && moment.isMoment(values[key][0])){
              //当元素为数组&&长度为2&&是moment对象,那么可以断定其是一个rangePicker
              values[`${key}StartDate`]=values[key][0].format('YYYY-MM-DD');
              values[`${key}EndDate`]=values[key][1].format('YYYY-MM-DD');
              values[key]=undefined;
          }

          if(moment.isMoment(values[key])){
              if(moment(values[key].format('YYYY-MM-DD'),'YYYY-MM-DD',true).isValid()){
                  values[key]=values[key].format('YYYY-MM-DD');
              }
          }
      }

        values=formatParams(values)
        this.setState({
          formValues: values,
          updateKey: Date.now(),
        }, () => {
          this.getKeyShowTemplate(values)
        });
      }
    });
  };

  handleFormReset=() => {
    this.props.form.resetFields();
    this.setState({
      formValues: {},
    }, () => {
      this.getKeyShowTemplate()
    });
  };

  initSock = () => {
    try {
        sock = new SockJS(`${window.wsURL}?token=${Cookies.get('token')}`);
        client = Stomp.over(sock);
        console.log('start');
        client.connect({},() => {
            try {
                client.subscribe(`/user/queue/notice/backlog`, (sockMessage) => {
                    if(sockMessage && this.handleSubmit){
                      this.handleSubmit()
                    }
                });
            } catch (err) {
                console.log(`webSocket subscribe失败:`);
                console.log(err);
            }

        // },(error)=>{
        //   console.log(error)
        });
    } catch (err) {
        console.log(`webSocket连接错误:`);
        console.log(err);
    }
  }

  destroySock = () => {
      try {
          client.disconnect();
      } catch (err) {
          console.log(`webSock销毁失败:`);
          console.log(err);
      }
      sock = null;
      client = null;
  }

  componentDidMount() {
    this.initSock()
  }

  componentWillUnmount(){
    this.destroySock()
  }

  render() {
    const { getFieldDecorator }=this.props.form;
    const formItemLayout={
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const { activeKey, formValues, updateKey }=this.state;
    const { home: { count } }=this.props;

    return (
      <PageHeaderWrapper
        title="待办事项"
      >
          <Form onSubmit={this.handleSubmit}>
              <Row gutter={4}>
                <Col span={8}>
                  <Form.Item
                      label="待办类型"
                    {...formItemLayout}
                  >
                    {getFieldDecorator('type', {
                    })(
                      <AsyncSelect
                        placeholder="请选择待办类型"
                        textFieldName="name"
                        valueFieldName="code"
                        url={`${window.baseURL}/api/v1/operate/info/getByType?name=待办&platform=2`}
                        transform={(data)=>{
                          const selAllData={
                            code: '',
                            name: '全部',
                          }
                          const nextData = (data && data.length>0) ? [...data] : [];
                            nextData.unshift(selAllData)
                            return nextData;
                        }}
                        style={{ width: '100%' }}
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="待办事项"
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('content', {
                    })(
                      <Input placeholder="请输入事项内容" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="产品线"
                    {...formItemLayout}
                  >
                    {getFieldDecorator('serviceId', {
                    })(
                      <AsyncSelect
                        placeholder="请选择产品线"
                        textFieldName="name"
                        valueFieldName="id"
                        url={`${window.baseURL}/api/v1/operate/info/getTreeByParentId?parentId=3`}
                        transform={(data)=>{
                          const selAllData={
                            id: '',
                            name: '全部',
                          }
                          const nextData=[...data];
                          nextData.unshift(selAllData)
                          return nextData || [];
                        }}
                        style={{ width: '100%' }}
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="公司"
                    {...formItemLayout}
                  >
                    {getFieldDecorator('companyCode', {
                    })(
                      <AsyncSelect
                        placeholder="请选择公司"
                        textFieldName="companyName"
                        valueFieldName="companyCode"
                        url={`${window.baseURL}/api/v1/operate/backlog/getBacklogCompanyList?status=${activeKey ==='todolist' ? 0 : 1}`}
                        transform={(data)=>{
                          const selAllData={
                            companyCode: '',
                            companyName: '全部',
                          }
                          const nextData=[...data];
                          nextData.unshift(selAllData)
                          return nextData || [];
                        }}
                        style={{ width: '100%' }}
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="日期"
                    {...formItemLayout}
                  >
                    {
                      getFieldDecorator('times', {
                    })(
                      <RangePicker style={{ width: '100%' }} />
                    )}
                  </Form.Item>
                </Col>
                <Col span={8} style={{ marginTop: "3px",textAlign:'right' }}>
                  <Button type="primary" htmlType="submit" style={{ marginLeft: 10 }}>查询</Button>
                  <Button onClick={this.handleFormReset} style={{ marginLeft: 10 }}>重置</Button>
                </Col>
              </Row>
            </Form>
          <Card
            className={styles.tabsCard}
            //extra={<a href="#">More</a>}
            bordered={false}
            tabList={tabList(count)}
            activeTabKey={activeKey}
            onTabChange={(key) => { this.onTabChange(key, 'activeKey'); }}
          >
            <StandardAsyncTable
              key={updateKey}
              showHeader={false}
              url={`${window.baseURL}/api/v1/operate/backlog/getBacklogList`}
              rowKey="id"
              params={{
                status: activeKey ==='todolist' ? 0 : 1,
                ...formValues
              }}
              title="页面列表页"
              columns={columns(this)}
            />
          </Card>

      </PageHeaderWrapper>
    )
  }
}

export default Dashboard
